package com.grantheath.erebus.model.loaders 
{
	import com.grantheath.erebus.view.interfaces.IErebusPage;
	import com.grantheath.erebus.model.interfaces.IErebusPageNode;
	import com.grantheath.erebus.model.interfaces.IErebusPageLoader;
	import com.grantheath.erebus.model.helpers.ErebusLoadEvent;
	
	import flash.net.URLRequest;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.events.IOErrorEvent;

	/**
	 * @author grantheath
	 */
	public class ErebusPageLoader extends Loader implements IErebusPageLoader
	{
		private var _pageNode : IErebusPageNode;
		
		public function ErebusPageLoader()
		{
			super();
			contentLoaderInfo.addEventListener(Event.OPEN, dispatchOpenEvent);
			contentLoaderInfo.addEventListener(Event.COMPLETE, dispatchCompleteEvent);
			contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, dispatchProgressEvent);
			contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, dispatchErrorEvent);
		}
		
		public function loadPage(pageNode : IErebusPageNode) : void
		{
			_pageNode = pageNode;
			load(new URLRequest(pageNode.pageSrc));
		}
		
		public function unloadPage() : void
		{
			close();
			unloadAndStop();
		}

		//EVENT HANDELERS
		public function dispatchOpenEvent(event : Event) : void
		{
			dispatchEvent(new ErebusLoadEvent(ErebusLoadEvent.LOAD_OPEN));
		}
		
		public function dispatchCompleteEvent(event : Event) : void
		{
			dispatchEvent(new ErebusLoadEvent(ErebusLoadEvent.LOAD_COMPLETE));
		}
		
		public function dispatchProgressEvent(event : Event) : void
		{
			dispatchEvent(new ErebusLoadEvent(ErebusLoadEvent.LOAD_PROGRESS));
		}

		public function dispatchErrorEvent(event : Event) : void
		{
			dispatchEvent(new ErebusLoadEvent(ErebusLoadEvent.LOAD_ERROR));
		}
		
		//GETTERS AND SETTERS
		public function get loadedPage() : IErebusPage
		{
			return contentLoaderInfo.content as IErebusPage;
		}
		
		public function get loadedBytesCount() : uint
		{
			return contentLoaderInfo.bytesLoaded;
		}
		
		public function get totalBytesCount() : uint
		{
			return contentLoaderInfo.bytesTotal;
		}
		
		public function get percentLoaded() : Number
		{
			if(totalBytesCount == 0){
				//prevents divide by zero errors
				return 0;
			}
			return (loadedBytesCount / totalBytesCount);
		}
		
		public function get pageNode() : IErebusPageNode
		{
			return _pageNode;
		}
		
		public function set pageNode(pageNode : IErebusPageNode) : void
		{
			_pageNode = pageNode;
		}
	}
}
